<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>双AI象棋对战系统-优化版</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chessboard-js/1.0.0/chessboard-1.0.0.min.css">
    <style>
        /* 保持原有样式不变 */
        :root {
            --ai1-color: #3498db;
            --ai2-color: #e74c3c;
            --neutral-color: #2c3e50;
            --background: #f8f9fa;
        }

        body {
            font-family: 'Segoe UI', system-ui, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background: var(--background);
            display: grid;
            grid-template-columns: 1fr 300px;
            gap: 30px;
        }

        /* 其他样式保持不变 */
    </style>
</head>
<body>
    <!-- 保持原有DOM结构 -->
    <div id="board-container">
        <div id="board"></div>
        <div class="eval-bar">
            <div class="eval-indicator" id="evalIndicator"></div>
        </div>
    </div>

    <div class="analysis-panel">
        <div class="control-group">
            <button id="startBtn">开始对战</button>
            <button id="pauseBtn">暂停</button>
            <button id="resetBtn">重置</button>
        </div>
        <!-- 分析面板内容保持不变 -->
    </div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chessboard-js/1.0.0/chessboard-1.0.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chess.js/0.10.3/chess.min.js"></script>

<script>
// 性能优化配置
const PERFORMANCE_CONFIG = {
    MAX_TASK_TIME: 50,    // 单次任务最大处理时间(ms)
    CHUNK_SIZE: 5,        // 消息分块处理数量
    DEBOUNCE_TIME: 300    // 按钮防抖时间
};

class GameEngine {
    constructor() {
        this.workers = {
            white: this.createWorker(),
            black: this.createWorker()
        };
        this.paused = false;
        this.pauseQueue = [];
    }

    createWorker() {
        const worker = new Worker('./stockfish.js');
        worker.postMessage('uci');
        worker.postMessage('setoption name Threads value 2');
        worker.postMessage('setoption name Hash value 256');
        return worker;
    }

    async sendCommand(color, command) {
        if (this.paused) {
            return new Promise(resolve => {
                this.pauseQueue.push(() => this._sendCommand(color, command).then(resolve));
            });
        }
        return this._sendCommand(color, command);
    }

    async _sendCommand(color, command) {
        const worker = this.workers[color];
        return new Promise((resolve, reject) => {
            const timeout = setTimeout(() => reject('Timeout'), 5000);
            
            const handler = (e) => {
                if (e.data === 'readyok' || e.data.startsWith('bestmove')) {
                    clearTimeout(timeout);
                    worker.removeEventListener('message', handler);
                    resolve(e.data);
                }
            };
            
            worker.addEventListener('message', handler);
            worker.postMessage(command);
        });
    }

    async pause() {
        this.paused = true;
        await Promise.all([
            this._sendCommand('white', 'stop'),
            this._sendCommand('black', 'stop')
        ]);
    }

    resume() {
        this.paused = false;
        while (this.pauseQueue.length) {
            this.pauseQueue.shift()();
        }
    }
}

class ChessGame {
    constructor() {
        this.initDependencies();
        this.engine = new GameEngine();
        this.game = new Chess();
        this.isRunning = false;
        this.moveHistory = [];
        this.config = {
            depth: 15,
            animationDuration: 300,
            moveDelay: 1500
        };

        this.initBoard();
        this.initEventListeners();
        this.initPerformanceMonitor();
    }

    initDependencies() {
        if (!window.Chess || !window.Chessboard) {
            throw new Error('依赖库未正确加载');
        }
    }

    initBoard() {
        this.board = Chessboard('board', {
            position: 'start',
            pieceTheme: 'img/{piece}.png',
            draggable: false,
            onTouchStart: () => this.handlePassiveEvent(),
            onTouchMove: () => this.handlePassiveEvent()
        });
    }

    handlePassiveEvent() {
        /* 被动事件处理 */
    }

    initEventListeners() {
        const passiveOptions = { passive: true };
        
        // 按钮事件
        $('#startBtn').on('click', () => this.debouncedStart());
        $('#pauseBtn').on('click', () => this.debouncedPause());
        $('#resetBtn').on('click', () => this.reset());

        // 触摸事件
        document.addEventListener('touchstart', this.handleTouchStart.bind(this), passiveOptions);
        document.addEventListener('touchmove', this.handleTouchMove.bind(this), passiveOptions);
    }

    debouncedStart() {
        if (!this.debounce('start')) return;
        this.start();
    }

    debouncedPause() {
        if (!this.debounce('pause')) return;
        this.togglePause();
    }

    debounce(action) {
        const now = Date.now();
        if (!this.lastActionTime) this.lastActionTime = 0;
        
        if (now - this.lastActionTime > PERFORMANCE_CONFIG.DEBOUNCE_TIME) {
            this.lastActionTime = now;
            return true;
        }
        return false;
    }

    async start() {
        if (this.isRunning) return;
        this.isRunning = true;
        
        try {
            while (this.isRunning && !this.game.game_over()) {
                const move = await this.getBestMove();
                await this.executeMove(move);
                this.updateGameState();
            }
        } catch (error) {
            this.handleError(error);
        }
    }

    async getBestMove() {
        const color = this.game.turn() === 'w' ? 'white' : 'black';
        const result = await this.engine.sendCommand(color, `go depth ${this.config.depth}`);
        return result.split(' ')[1];
    }

    async executeMove(move) {
        return new Promise(resolve => {
            this.animateMove(move, () => {
                this.game.move(move, { sloppy: true });
                this.board.position(this.game.fen());
                resolve();
            });
        });
    }

    animateMove(move, callback) {
        const [from, to] = [move.substring(0,2), move.substring(2,4)];
        const $piece = $(`[data-square="${from}"] .piece`);
        const targetPos = $(`[data-square="${to}"]`).offset();

        $piece.css({
            transition: `all ${this.config.animationDuration}ms ease-out`,
            transform: `translate(${targetPos.left}px, ${targetPos.top}px)`,
            zIndex: 1000
        });

        setTimeout(() => {
            $piece.css({ transform: 'none', zIndex: 'auto' });
            callback();
        }, this.config.animationDuration);
    }

    async togglePause() {
        if (this.isRunning) {
            await this.engine.pause();
            this.isRunning = false;
        } else {
            this.engine.resume();
            this.isRunning = true;
            this.start();
        }
        this.updateControlButtons();
    }

    updateControlButtons() {
        $('#pauseBtn').text(this.isRunning ? '暂停' : '继续');
    }

    updateGameState() {
        const evalDiff = this.calculateEvaluation();
        $('#evalIndicator').css('left', `${50 + evalDiff * 3}%`);
    }

    calculateEvaluation() {
        /* 评估计算逻辑 */
        return 0;
    }

    reset() {
        this.isRunning = false;
        this.game.reset();
        this.board.position('start');
        this.engine.resume();
    }

    initPerformanceMonitor() {
        if (window.PerformanceObserver) {
            const observer = new PerformanceObserver(list => {
                list.getEntries().forEach(entry => {
                    if (entry.duration > 100) {
                        console.warn(`长任务警告: ${entry.name} 用时 ${entry.duration.toFixed(1)}ms`);
                    }
                });
            });
            observer.observe({ entryTypes: ['longtask'] });
        }
    }

    handleError(error) {
        console.error('游戏错误:', error);
        this.isRunning = false;
        alert(`发生错误: ${error.message}`);
    }
}

// 初始化游戏
$(document).ready(() => {
    try {
        window.game = new ChessGame();
    } catch (error) {
        console.error('初始化失败:', error);
        alert('系统初始化失败，请检查控制台日志');
    }
});
</script>
</body>
</html>